package com.leetcode.partition2;

import com.leetcode.common.TreeNode;

import java.util.LinkedList;

/**
 * @author `RKC`
 * @date 2021/8/17 10:05
 */
public class LC111二叉树的最小深度 {

    public int minDepth(TreeNode root) {
        return recursion(root);
    }

    private int iteration(TreeNode root) {
        if (root == null) return 0;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int minDepth = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode current = queue.pollFirst();
                if (current.left != null) queue.add(current.left);
                if (current.right != null) queue.add(current.right);
                //当左右孩子都为空的时候，说明是最底点的一层
                if (current.left == null && current.right == null) return 1 + minDepth;
            }
            minDepth++;
        }
        return minDepth;
    }

    private int recursion(TreeNode root) {
        if (root == null) return 0;
        int leftDepth = recursion(root.left);
        int rightDepth = recursion(root.right);
        //当左子树为空，右不为空，这时并不是最低点
        if (root.left == null && root.right != null) return 1 + rightDepth;
        //当左子树不为空，右为空，也不是最低点
        if (root.left != null && root.right == null) return 1 + leftDepth;
        return 1 + Math.min(leftDepth, rightDepth);
    }
}
